/**
 * 创建企业--js
 * @author xiangfei
 * @date 2019年3月27日
 */
var enterprise_add = {
    data : {
        obj: {}, // 保存后会将保存的对象保存在这里，可以拿到id和uuid
        saved : false, // 是否保存新建的企业，没保存无法进行下面附件丶进度丶项目的操作
        industry : [], // 行业信息
        // 企业需求统一放在这里，urgent是紧急  commonly是一般
        entNeeds : [{
            id : "need_id_0",
            text : "",
            degree : "urgent"
        },{
            id : "need_id_1",
            text : "",
            degree : "commonly"
        }]
    },
    /**
     * 初始化，包括初始化日期选择框，初始化需求的输入框列表，获取行业大类
     */
    init : function() {
        enterprise_add.initDatePicker();
        enterprise_add.initNeeds();
        enterprise_add.getAllIndustryParent();
    },
    /**
     * 日期初始化
     */
    initDatePicker : function(){
        laydate.render({
            elem: '#entOneBirthday' //生日1
        });
        laydate.render({
            elem: '#entTwoBirthday' //生日2
        });
    },
    /**
     * 获取所有行业大类供选择
     */
    getAllIndustryParent : function() {
        $.ajax({
            url : "/crm/industry/findAllParent",
            dataType : "json",
            type : "get",
            success : function(res) {
                if(res.length > 0) {
                    enterprise_add.data.industry = res;
                    var industryOptions = "";
                    for(var i = 0 ; i < res.length ; i ++) {
                        industryOptions += '<option value="' + res[i].uuid + '">'+res[i].indName+'</option>'
                    }
                    $("#entIndustryOne").append(industryOptions);
                }
            },
            error : function() {
                layer.alert("获取行业信息错误！", {icon: 2, closeBtn: 0 }, function(index) {
                    layer.close(index);
                });
            }
        });
    },
    /**
     * 获取页面上所有的企业需求，并赋值编好顺序的id，返回对象数组给调用者
     * @returns {Array}
     */
    getAllNeeds : function(){
        var length = $(".needs").length;
        var needs = [];
        for(var i = 0 ; i < length ; i ++) {
            needs.push({
                id : "need_id_" + i,
                text : $(".needs input")[i].value,
                degree : $(".needs select")[i].value
            });
        }
        return needs;
    },
    /**
     * 渲染需求列表,拼接好后先移除旧的，再添加渲染好的
     */
    initNeeds : function() {
        var html = "";
        for(var i = 0 ; i < enterprise_add.data.entNeeds.length ; i ++) {
            html +=
                '<div class="cr_tj needs" id="need_tr_'+i+'">'+
                    '<dl>'+
                        '<dt class="'+(i===0?"":"no_label")+'" id="need_title_'+i+'">'+(i === 0 ? "企业需求：" : "")+'</dt>'+
                        '<dd>'+
                            '<input type="text" id="need_text_'+i+'" value="'+enterprise_add.data.entNeeds[i].text+'">'+
                            '<select id="need_degree_'+i+'">'+
                                '<option value="urgent" '+(enterprise_add.data.entNeeds[i].degree === "urgent" ? "selected" : "")+'>紧急</option>'+
                                '<option value="commonly" '+(enterprise_add.data.entNeeds[i].degree === "commonly" ? "selected" : "")+'>一般</option>'+
                            '</select>'+
                            '<button class="btn_add" onclick="enterprise_add.addNeed()">添加</button>'+
                            '<button class="btn_del" onclick="enterprise_add.deleteNeed(\'need_id_'+i+'\')">删除</button>'+
                        '</dd>'+
                    '</dl>'+
                '</div>';
        }
        $(".needs").remove();
        $("#operation").before(html);
    },
    /**
     * 刷新企业需求列表，一般发生在删除需求后
     */
    refreshNeeds : function() {
        enterprise_add.data.entNeeds = enterprise_add.getAllNeeds(); // 获取页面上现有的需求，
        enterprise_add.initNeeds();
    },
    /**
     * 添加需求,默认是紧急的
     */
    addNeed : function() {
        var i = enterprise_add.data.entNeeds.length;
        var html =
            '<div class="cr_tj needs" id="need_tr_'+i+'">'+
                '<dl>'+
                    '<dt class="no_label" id="need_title_'+i+'"></dt>'+
                    '<dd>'+
                        '<input type="text" id="need_text_'+i+'">'+
                        '<select id="need_degree_'+i+'">'+
                            '<option value="urgent">紧急</option>'+
                            '<option value="commonly">一般</option>'+
                        '</select>'+
                        '<button class="btn_add" onclick="enterprise_add.addNeed()">添加</button>'+
                        '<button class="btn_del" onclick="enterprise_add.deleteNeed(\'need_id_'+i+'\')">删除</button>'+
                    '</dd>'+
                '</dl>'+
            '</div>';
        $("#operation").before(html);
        enterprise_add.data.entNeeds.push({
            id : "need_id_" + i,
            text : "",
            degree : "urgent"
        });
    },
    /**
     * 删除需求，需要传入id，这里的id一般指DOM上按钮渲染的id
     * @param id
     */
    deleteNeed : function(id) {
        if(enterprise_add.data.entNeeds.length > 2) {
            $("#need_tr_"+id.slice(id.lastIndexOf("_")+1,id.length)).remove();
            for(var i = 0 ; i < enterprise_add.data.entNeeds.length ; i ++){
                if(id === enterprise_add.data.entNeeds[i].id){
                    enterprise_add.data.entNeeds.splice(i,1);
                }
            }
            enterprise_add.refreshNeeds();
        } else {
            // layer.msg("最少保留两个需求");
        }
    },
    /**
     * 新增企业的保存
     */
    addSave : function(_this){
        var that = _this;
        var entName = $("#entName").val();
        var entAddress = $("#entAddress").val();
        var entOnePerson = $("#entOnePerson").val();
        var entOnePhone = $("#entOnePhone").val();
        var entOneBirthday = $("#entOneBirthday").val();
        var entTwoPerson = $("#entTwoPerson").val();
        var entTwoPhone = $("#entTwoPhone").val();
        var entTwoBirthday = $("#entTwoBirthday").val();
        var entIndustryOne = $("#entIndustryOne").val();
        var entIndustryTwo = $("#entIndustryTwo").val();
        var entUpstream = $("#entUpstream").val();
        var entDownstream = $("#entDownstream").val();
        var entStockRight = $("#entStockRight").val();
        var entProduct = $("#entProduct").val();
        var entMode = $("#entMode").val();


        if(enterprise_add.isBlank(entName)) {
            layer.msg("请输入名称");
            return false;
        }
        if(enterprise_add.isBlank(entAddress)) {
            layer.msg("请输入地址");
            return false;
        }
        if(enterprise_add.isBlank(entOnePerson)) {
            layer.msg("请输入联系人1姓名");
            return false;
        }

        if(!enterprise_add.phoneAvailable(entOnePhone)) {
            layer.msg("请正确输入电话号码");
            return false;
        }


        var obj = {};
        obj.entName = entName;
        obj.entAddress = entAddress;
        obj.entOnePerson = entOnePerson;
        obj.entOnePhone = entOnePhone;

        obj.entOneBirthday = entOneBirthday;
        obj.entTwoPerson = entTwoPerson;
        obj.entTwoPhone = entTwoPhone;
        obj.entTwoBirthday = entTwoBirthday;
        /**
         * 行业大类的处理
         * @type {*|jQuery}
         */
        if(entIndustryOne && !isBlank(entIndustryOne)) {
            for(var j = 0 ; j < enterprise_add.data.industry.length ; j ++) {
                if(enterprise_add.data.industry[j].uuid === entIndustryOne) {
                    obj.entIndustryOne = JSON.stringify(enterprise_add.data.industry[j]);
                }
            }
        }
        obj.entIndustryTwo = entIndustryTwo;
        obj.entUpstream = entUpstream;
        obj.entDownstream = entDownstream;
        obj.entStockRight = entStockRight;
        obj.entProduct = entProduct;
        obj.entMode = entMode;
        /**
         * 需求的处理
         * @type {*|jQuery}
         */
        var entNeedsUrgent = [];
        var entNeedsCommonly = [];
        var needs = enterprise_add.getAllNeeds();
        for(var i = 0 ; i < needs.length ; i ++) {
            if(!enterprise_add.isBlank(needs[i].text)) {
                if(needs[i].degree === "urgent") {
                    entNeedsUrgent.push(needs[i].text);
                } else if (needs[i].degree === "commonly") {
                    entNeedsCommonly.push(needs[i].text);
                }
            }
        }
        obj.entNeedsUrgent = JSON.stringify(entNeedsUrgent);
        obj.entNeedsCommonly = JSON.stringify(entNeedsCommonly);

        // 准备保存,按钮先去掉点击属性，防止多次点击多次保存，保存成功后不再可点击，如果出错可以再次点击
        $(_this).attr("onclick", "");
        $(_this).css("background", "#c0c1c0");
        $.ajax({
            url : "/crm/enterprise/save",
            dataType : "json",
            data : obj,
            type : "post",
            success : function(res) {
                if(res.status) {
                    layer.alert(res.info, {icon: 1, closeBtn: 0 }, function(index) {
                    	parent.refreshTabByIndex(0);
                        // parent.closeCurPage();
                       // enterprise_add.data.obj = res.obj;
                       // enterprise_add.data.saved = true;
                        // 初始化附件/进度/项目的js
                       // ent_associated_add.initAfterEntSaved(enterprise_add.data.obj);
                        layer.close(index);
                    });
                } else {
                    layer.alert(res.info, {icon: 2, closeBtn: 0 }, function(index) {
                        $(that).attr("onclick","enterprise_add.addSave(this)");
                        $(that).css("background","#d53638");
                        layer.close(index);
                    });
                }
            },
            error : function() {
                layer.alert("系统错误！", {icon: 2, closeBtn: 0 }, function(index) {
                    $(_this).attr("onclick","enterprise_add.addSave(this)");
                    $(_this).css("background","#d53638");
                    layer.close(index);
                });
            }
        });
    },
    /**
     * 重置所有输入
     * @param _this
     */
    reset : function(_this) {
        var _that = _this;
        layer.confirm("确定重置吗?所有输入将清空.", {icon: 3, title:'请确认'}, function (index) {
            $("#enterprise_add_div input").val("");
            enterprise_add.data.entNeeds = [{
                id : "need_id_0",
                text : "",
                degree : "urgent"
            },{
                id : "need_id_1",
                text : "",
                degree : "commonly"
            }];
            enterprise_add.initNeeds();
            layer.close(index);
        });

    },
    /**
     * 校验手机号码是否合法
     * @param phone phone
     * @returns {boolean} 合法返回true,否则false
     */
    phoneAvailable : function (phone) {
        var reg = /^[1][3,4,5,7,8][0-9]{9}$/;
        return reg.test(phone);
    },
    /**
     * 判断字符串是否空值
     * @param str 传入参数
     * @returns {boolean} 空返回true   不空false
     */
    isBlank : function (str) {
        return (typeof str === "undefined" || str === "undefined" || str === null || str === "null" || str === "" || str.length <= 0);
    }
};